package com.hula.onion.book.server.alarm.service.impl;

import com.hula.onion.book.server.alarm.common.ConfigConstants;
import com.hula.onion.book.server.alarm.dingtalk.DingtalkChatbotClient;
import com.hula.onion.book.server.alarm.dingtalk.message.MarkdownMessage;
import com.hula.onion.book.server.alarm.service.ICommonAlertService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * Description:钉钉告警服务
 * Create Date:2018/3/1 11:01
 *
 * @author liangbing
 * @version 1.0
 */
@Service
public class DingTalkAlertServiceImpl implements ICommonAlertService {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(DingTalkAlertServiceImpl.class);

    @Override
    public void alarm(String alarmLevel, String title, String msg, List<String> toUserEmail) {

        //[alarmLevel] + title
        if (StringUtils.isEmpty(alarmLevel)) {
            alarmLevel = "Error";
        }

        title = "[" + alarmLevel + "] " + title;

        DingtalkChatbotClient client = new DingtalkChatbotClient();

        MarkdownMessage message = new MarkdownMessage();

        message.setTitle(title);
        message.add(MarkdownMessage.getHeaderText(3, title));
        message.add("\n\n");
        message.add(">- **" + msg + "**");
        message.add("\n\n");

        try {
            client.send(ConfigConstants.WEB_HOOK, message);
        } catch (IOException e) {
            LOGGER.error("Dingtalk send message error!", e.getMessage());
        }

    }
}
